package com.waya.web.browser.event;

import android.view.KeyEvent;
import android.webkit.WebView;

import java.lang.ref.WeakReference;

/**
 * Created by JesseHev on 2018/1/11.
 * describe: webview事件处理
 */

public class EventHandlerImp implements IEventHandler {

    private static volatile EventHandlerImp INSTANCE = null;

    private WebView webview;

    String url;

    public EventHandlerImp(WebView webview, String url) {
        this.webview = webview;
        this.url = url;
    }

    public static EventHandlerImp getInstance(WebView webview, String url) {
        if (INSTANCE == null) {
            synchronized (EventHandlerImp.class) {
                INSTANCE = new EventHandlerImp(webview, url);
            }
        }
        return INSTANCE;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return back();
        }
        return false;
    }

    @Override
    public boolean back() {
        if (webview != null && webview.canGoBack()) {
            if (webview.getUrl().equals(url)) {
                return false;
            } else {
                webview.goBack();
                return true;
            }
        } else {
            return false;
        }
    }
}
